package com.situ.web.controller;

import com.situ.web.pojo.Banji;
import com.situ.web.service.IBanjiService;
import com.situ.web.service.impl.BanjiServiceImpl;
import com.situ.web.util.JSONUtil;
import com.situ.web.util.LayUITableResult;
import com.situ.web.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/banji")
public class BanjiServlet extends HttpServlet {
    private IBanjiService banjiService = new BanjiServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "selectAll":
                selectAll(req, resp);
                break;
        }
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BanjiServlet.selectAll");
        List<Banji> list = banjiService.selectAll();
        JSONUtil.toJSON(resp, Result.ok(list));
    }

    //https://layui.itze.cn/demo/table/user.json?page=1&limit=10
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BanjiServlet.selectByPage");
        String pageStr = req.getParameter("page");
        if (pageStr == null || pageStr.equals("")) {
            pageStr = "1";
        }
        String limitStr = req.getParameter("limit");
        if (limitStr == null || limitStr.equals("")) {
            limitStr = "5";
        }
        int page = Integer.parseInt(pageStr);
        int limit = Integer.parseInt(limitStr);

        LayUITableResult layUITableResult = banjiService.selectByPage(page, limit);

        JSONUtil.toJSON(resp, layUITableResult);
    }
}
